package com.sheep.opt;


import org.apache.ibatis.io.Resources;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.Reader;
import java.sql.Connection;

/**
 * Created by IntelliJ IDEA.
 * User: wnj
 * Date: 2010-11-13
 * Time: 15:56:23
 * To change this template use File | Settings | File Templates.
 */
public class SessionManager {
    private static final String resource = "/sql_map_config.xml";
    private static final String environment = "development";
    private static SqlSessionFactory sqlMapper;

    public static SqlSession openSession(boolean autocommit, String env) {
        if (sqlMapper == null) {
            try {
                Reader reader = Resources.getResourceAsReader(SessionManager.resource);
                sqlMapper = new SqlSessionFactoryBuilder().build(reader, env);
                

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            Connection conn = ThreadUtil.currentConnWnj();
            conn.setAutoCommit(autocommit);
            return sqlMapper.openSession(conn);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static SqlSession openSession(boolean autocommit) {
        return openSession(autocommit, environment);
    }

    public static SqlSession openSession() {
        return openSession(true);
    }
}
